#DP
import urllib
from random import randrange
import base64
import struct

class Base:

	def __init__(self, my_email, user_instance, session_instance):
		self.user = user_instance
		self.my_email = my_email
		self.session = session_instance
		self.object = urllib.unquote(self.user.msn_object)
		self.object  += "\x00"
		self.base_id = randrange(1,1000)
	

	def create_header(self, f1=0, f2=0, f3=0, f4=0, f5=0, f6=0, f7=0, f8=0, f9=0):
	
		one = struct.pack("<I", f1)
		two = struct.pack("<I", f2)
		three = struct.pack("<Q", f3)
		four = struct.pack("<Q", f4)
		five = struct.pack("<I", f5)
		six = struct.pack("<I", f6)
		seven = struct.pack("<I", f7)
		eight = struct.pack("<I", f8)
		nine = struct.pack("<Q", f9)

		header = one + two + three + four + five + six + seven + eight + nine
		return header

	def invitation(self):
		print "Got invitation"
		f7 = randrange(1,100)
		msn_object = base64.b64encode(self.object)

		msnlp_body = """
			\r\n
			EUF-GUID: {A4268EEC-FEC5-49E5-95C3-F126696BDBF6}\r\n
			SessionID: """+self.session.id+"""\r\n
			AppID: 1\r\n0x00 0x00 0x00 0x00
			Context: """+msn_object+"""\r\n
			\r\n
			"""

		msnlp_header = """
			INVITE MSNMSGR:"""+self.user.email+""" MSNSLP/1.0\r\n
			To: <msnmsgr:"""+self.user.email+""">\r\n
			From: <msnmsgr:"""+self.my_email+""">\r\n
			Via: MSNSLP/1.0/TLP ;branch={33517CE4-02FC-4428-B6F4-39927229B722}\r\n
			CSeq: 0 \r\n
			Call-ID: {9D79AE57-1BD5-444B-B14E-3FC9BB2B5D58}\r\n
			Max-Forwards: 0\r\n
			Content-Type: application/x-msnmsgr-sessionreqbody\r\n
			Content-Length: """+str(len(msnlp_body))+"""\r\n"""

		footer = "0x00 0x00 0x00 0x00"

		msnlp = msnlp_header + msnlp_body
		binary_header = self.create_header(0,self.base_id,0,len(msnlp), len(msnlp),0,f7,0,0)
		mime =  """
			MIME-Version: 1.0\r\n
			Content-Type: application/x-msnmsgrp2p\r\n
			P2P-Dest: """+self.user.email+"""\r\n
			\r\n
			"""
		total = mime + binary_header + msnlp + footer
		total = "MSG "+str(self.session.tr_id)+" D "+str(len(total))+"\r\n"
		print repr(total)
		self.session._sync(total)
			
